//
//  SearchViewController.m
//  ShunTian
//
//  Created by zhanshu on 15/8/28.
//  Copyright (c) 2015年 zhanshu. All rights reserved.
//



#import "SearchViewController.h"
#import "ProductCollectionView.h"
#import "ShowSearchVC.h"
#import "CategorySubVC.h"
#import "SubProductManagerViewController.h"
#import "ZBarScanVC.h"
#import <AVFoundation/AVFoundation.h>
#import <MobileCoreServices/MobileCoreServices.h>
@interface SearchViewController ()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate,SearchProductDelegate,SendNumDelegate>
{
    NSMutableArray *productsArr;
}
@property (weak, nonatomic) IBOutlet UIView *searchBackView;
@property (weak, nonatomic) IBOutlet UITextField *searchTextField;

@property (weak, nonatomic) IBOutlet UITableView *searchTableView;
@property (strong, nonatomic) NSArray *recordArr;
@property (strong, nonatomic) ProductCollectionView *prodictCV;

@property (weak, nonatomic) IBOutlet UITextField *searchTextF;

@property (weak, nonatomic) IBOutlet UIImageView *noProductImg;//没有商品时显示的图片

@end

@implementation SearchViewController
-(void)viewDidAppear:(BOOL)animated {
    [self.searchTextField becomeFirstResponder];
}
- (void)resetView {
    [self.view insertSubview:_noProductImg aboveSubview:_prodictCV];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navBar.hidden = YES;
    //刷新数据
    [self reloadData];
    [self setupSearchView];
    productsArr = [[NSMutableArray alloc] init];
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    _prodictCV = [[ProductCollectionView alloc] initWithFrame:CGRectMake(0, 70, ScreenWidth, ScreenHeight-64) collectionViewLayout:layout];
    _prodictCV.hidden = YES;
    _prodictCV.searchProductDelegate = self;
    if (self.searchType == TypeProductsLib || self.searchType == TypeProductsManager)
    {
        self.codeBtn.hidden = NO;
        _searchTextF.placeholder = @"搜索商品名称/商品条码";
    }else {
        self.codeBtn.hidden = YES;
        _searchTextF.placeholder = @"商品名称/订单号/手机号";
    }
    [_searchTextF addTarget:self action:@selector(textFDidChanged:) forControlEvents:UIControlEventEditingChanged];
    [self.view addSubview:_prodictCV];
    [self resetView];
}
- (void)textFDidChanged:(UITextField *)textField
{
    if (self.searchType == TypeProductsLib || self.searchType == TypeProductsManager)
    {
        if (textField.text.length == 0) {
            self.codeBtn.hidden = NO;
        }else {
            self.codeBtn.hidden = YES;
        }
    }
}
- (void)setupSearchView
{
    _searchBackView.layer.cornerRadius = 5;
    _searchBackView.layer.borderWidth = 1;
    _searchBackView.layer.borderColor = SetColor(204, 204, 204, 1).CGColor;
    _searchTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    _searchTextField.delegate = self;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _recordArr.count+1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 40;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    return @"搜索历史";
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *Cell = @"cell";
    UITableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:Cell];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:Cell];
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake((ScreenWidth)/2 - 60.5, 7, 121, 26);
        [btn setImage:[UIImage imageNamed:@"deletemamery"] forState:UIControlStateNormal];
        btn.tag = 100;
        btn.hidden = YES;
        [btn addTarget:self action:@selector(deleteRecord) forControlEvents:UIControlEventTouchUpInside];
        [cell.contentView addSubview:btn];
    }
    if (_recordArr.count>0) {
        UIButton *btn = (UIButton*)[cell.contentView viewWithTag:100];
        if (indexPath.row == _recordArr.count) {
            btn.hidden = NO;
            cell.textLabel.text = @"";
        }else {
            btn.hidden = YES;
            cell.textLabel.textAlignment = NSTextAlignmentLeft;
            cell.textLabel.text = [_recordArr objectAtIndex:indexPath.row];
        }
    }
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    [self.view endEditing:YES];
    if (indexPath.row == _recordArr.count) {
        //清空搜索记录
        [NSUserDefualManager storageValue:@[] forKey:SearchRecord];
        [self reloadData];
    }else {
        _searchTextField.text = _recordArr[indexPath.row];
        self.codeBtn.hidden = YES;
        [self getMess];
    }
}
- (void)reloadData {
    _recordArr = [NSUserDefualManager getValueByKey:SearchRecord];
    if (_recordArr.count > 0) {
        _searchTableView.hidden = NO;
        [_searchTableView reloadData];
    }else {
        _searchTableView.hidden = YES;
    }
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    [self.view endEditing:YES];
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    [self.view endEditing:YES];
}
#pragma mark - 搜索获取数据
- (void)getMess {
    if (self.searchType == TypeProductsManager) { // productManager
        SubProductManagerViewController* productManagerVC = [[SubProductManagerViewController alloc]init];
        productManagerVC.keyWord = _searchTextField.text;
        productManagerVC.isSearchVC = @"YES";
        productManagerVC.isHotVC = self.isHotVC;
        [self.navigationController pushViewController:productManagerVC animated:YES];
    }else if (self.searchType == TypeProductsLib){ // TypeProductsLib
        CategorySubVC *categoryVC = [[CategorySubVC alloc]init];
        categoryVC.isShowSearch = @"YES";
        categoryVC.keyWorlds = _searchTextField.text;
        [self.navigationController pushViewController:categoryVC animated:YES];
    }else { // TypeOther
        ShowSearchVC *order = [[ShowSearchVC alloc] init];
        order.keyWord = _searchTextField.text;
        [self.navigationController pushViewController:order animated:YES];
    }
    
//    if ([_productLibStr isEqualToString:@"YES"]) {
//        CategorySubVC *categoryVC = [[CategorySubVC alloc]init];
//        categoryVC.isShowSearch = @"YES";
//        categoryVC.keyWorlds = _searchTextField.text;
//        [self.navigationController pushViewController:categoryVC animated:YES];
//    }else {
//        ShowSearchVC *order = [[ShowSearchVC alloc] init];
//        order.keyWord = _searchTextField.text;
//        [self.navigationController pushViewController:order animated:YES];
//    }
}
#pragma mark - 清除历史记录
- (void)deleteRecord {
    [NSUserDefualManager storageValue:@[] forKey:SearchRecord];
    [self reloadData];
}
#pragma mark - 搜索事件
- (IBAction)searchAction:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)searchManager {
    [self.view endEditing:YES];
    if (_searchTextField.text.length == 0) {
        [[MessShowView share] showWithMess:@"搜索内容不能为空"];
        return;
    }
    if (_searchTextField.text.length != 0) {
        //不能为空
        NSString *changedStr = [_searchTextField.text stringByReplacingOccurrencesOfString:@" " withString:@""];
        if (changedStr.length != 0) {
            [NSUserDefualManager addNewRecord:_searchTextField.text forKey:SearchRecord];
        }
    }
    [self reloadData];
    [self getMess];
}
#pragma mark - UITextField 
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    //搜索事件
    [self searchManager];
    return YES;
}
- (BOOL)textFieldShouldClear:(UITextField *)textField {
    _prodictCV.hidden = YES;
    _searchTableView.hidden = NO;
    _noProductImg.hidden = YES;
    return YES;
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
-(BOOL)isCammer
{
    NSString *mediaType = AVMediaTypeVideo;
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
    if(authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied){
        
        //NSLog(@"相机权限受限");
        return NO;
    }else{
        //NSLog(@"相机可以使用");
        return YES;
    }
}

#pragma mark --- 没有调用相机的权限提示
-(void)noCameraReminder
{
    UIAlertView *alert;
    if ([[[UIDevice currentDevice] systemVersion] floatValue] < 8.0) {
        alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                           message:@"如果你想继续使用相机，请在iPhone的“设置”-“隐私”-“相机”中，找到懒猫社长商家版允许"
                                          delegate:nil
                                 cancelButtonTitle:@"确定"
                                 otherButtonTitles:nil, nil];
    } else {
        alert = [[UIAlertView alloc]initWithTitle:@"您没有访问相机权限" message:@"如果你想继续使用相机，请在iPhone的“设置”-“隐私”-“照片”中，找到懒猫社长商家版允许" delegate:self cancelButtonTitle:@"不允许" otherButtonTitles:@"前往", nil];
        alert.tag = 7780;
        [alert show];
        
    }
    
}
- (IBAction)codeBtn:(UIButton *)sender {
    if ([self isCammer]) {
        ZBarScanVC *zbar = [[ZBarScanVC alloc] init];
        
        zbar.delegate = self;
        [self.navigationController pushViewController:zbar animated:YES];
    }else{
        [self noCameraReminder];
        return;
    }
}
- (void)senNum:(NSString *)num
{
    _searchTextField.text = num;
    NSLog(@"%@",num);
}

@end
